package com.apexedu.portal.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.apexedu.biz.Const;
import com.apexedu.framework.jdbc.DataSourceEntity;
import com.apexedu.framework.jdbc.DataSourceManager;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.action.IdLoginAction;
import com.apexedu.portal.action.PortalDBAction;
import com.apexedu.portal.entity.TDb;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;

/**
 * Created by janabo on 2014-10-9.
 */
@Service("portalDbService")
public class PortalDbServiceImpl extends AbstractBaseServiceSupport {

	@SuppressWarnings("unchecked")
	@Override
	public List<TDb> list(Object myaction, Pager pager) throws Exception {
		long c = DBUtil.count("select count(*) as c from t_db t ");
		pager.setTotalRows(c);
		List<TDb> list = DBUtil.queryPageBeanList(pager, "select * from t_db t", TDb.class);
		return list;
	}

	@Override
	public void saveOrUpdate(Object myaction) throws Exception {
		PortalDBAction action = (PortalDBAction) myaction;
		TDb tdb = action.getTdb();
		if (tdb != null) {
			if (StringUtil.isNotBlank(tdb.getWid())) {
				baseDao.updateNotNull(tdb);
				BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_DB, Const.LOG_ACTION_UPDATE, IdLoginAction.getIpAddr(action.getRequest()), "修改数据源");
			} else {
				tdb.setWid(SeqFactory.getNewSequenceAlone());
				baseDao.save(tdb);
				BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_T_DB, Const.LOG_ACTION_SAVE, IdLoginAction.getIpAddr(action.getRequest()), "新增数据源");
			}

			try {//获取数据库连接，获取到时更新
				DataSourceManager.getDataSource(tdb.getCode());

				DataSourceEntity entity = new DataSourceEntity();
				entity.setDataSourceName(tdb.getCode());
				entity.setDriver(tdb.getDriver());
				entity.setUrl(tdb.getUrl());
				entity.setUsername(tdb.getUsername());
				entity.setPassword(tdb.getPwd());
				entity.setMinPoolSize(3);
				DataSourceManager.putNewDataSource(entity);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
		}
	}

	@Override
	public void load(Object myaction) throws Exception {
		PortalDBAction action = (PortalDBAction) myaction;
		String wid = action.getWid();
		TDb tdb = DBUtil.queryBean("select * from t_db tb where tb.wid = ?", TDb.class, wid);
		action.setTdb(tdb);
	}

	@Override
	public boolean remove(Object myaction) throws Exception {
		return false;
	}
}
